//
//  Radio.m
//  WWXELuShang
//
//  Created by lanou on 15/12/19.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "Radio.h"

@implementation Radio

- (AVPlayer *)player{
    if (!_player) {
        _player = [[AVPlayer alloc]init];
    }
    return _player;
}




+ (Radio *)shareJsonWithDictionary:(NSDictionary *)dictionary{
    Radio *radio = [[Radio alloc]init];
    [radio setValuesForKeysWithDictionary:dictionary];
    return radio;
}


static Radio *radio;
+ (Radio *)shareWithRadio{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        radio = [[Radio alloc]init];
    });
    return radio;
}


- (void)setValue:(id)value forUndefinedKey:(NSString *)key{
    if ([key isEqualToString:@"id"]) {
        self.ID = [NSString stringWithFormat:@"%@",value];
    }
}

//根据url播放一首歌
- (void)playWithUrl:(NSString *)url{
    
    if (self.playerItem) {
        [self.playerItem removeObserver:self forKeyPath:@"stauts"];

    }
    
    self.playerItem = [[AVPlayerItem alloc]initWithURL:[NSURL URLWithString:url]];
    [self.playerItem addObserver:self forKeyPath:@"stauts" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    [self.player replaceCurrentItemWithPlayerItem:self.playerItem];
    
}







- (void)starPlayRadio{
    
    if (self.isReadyToPlay == YES) {
        AVAudioSession *session = [[AVAudioSession alloc]init];
        [session setActive:YES error:nil];
        [session setCategory:AVAudioSessionCategoryPlayback error:nil];
        
        
        [self playWithUrl:self.radioinfourl];
        [self.player play];
     
        
    }
    
}

- (void)stopRadio{
    [self.player pause]; //停止播放
    self.isReadyToPlay = NO;
    
}





- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    
    switch ([change[@"new"] integerValue]) {
        case AVPlayerItemStatusFailed:
            NSLog(@"缓冲失败");
            break;
        case AVPlayerItemStatusReadyToPlay:
            NSLog(@"缓冲成功");
            self.isReadyToPlay = YES;
            
            //发送一个通知：缓冲成功，可以开始播放
            [[NSNotificationCenter defaultCenter] postNotificationName:@"readyToPlay" object:nil];
            break;
            
        case AVPlayerItemStatusUnknown:
            NSLog(@"缓冲状态未知");
            break;
        default:
            break;
    }
}




@end
